<template>
    <div class="view">
        <nav-bar title="编辑收货地址" @clickLeft="back" @clickRight="save" :fixed="false" class="address-nav-bar">
            <div class="back" slot="left">
                <i class="iconfont icon-fanhui"></i>
            </div>
            <div class="save" slot="right">
                保存
            </div>
        </nav-bar>

        <div class="address-content">
            <div class="address-content-row">
                <span class="title">联系人</span>
                <input class="input" type="text" placeholder="收货人姓名" v-model="addressData.detail.name"/>
            </div>
            <div class="address-content-row">
                <span class="title">手机号</span>
                <input class="input" type="number" placeholder="收货人手机号码" v-model="addressData.detail.phone"/>
            </div>
            <div class="address-content-row ">
                <span class="title">地区</span>
                <span class="div-input" @click="showCascadePicker" :style="regionText!=='  '?'color:#333':''">{{regionText!=='  '?regionText:'所在地区'}}</span>
                <span class="iconfont icon-weibiaoti2fuzhi08"></span>
            </div>
            <div class="address-content-row">
                <span class="title">详细地址</span>
                <input class="input" type="text" placeholder="街道、楼号、门牌" v-model="addressData.detail.detail"/>
            </div>

            <div class="address-content-row default-address-row">
                <span class="title">设为默认</span>
                <cube-switch class="default-address-switch" :disabled="disabled" v-model="isDefault"></cube-switch>
            </div>
            <div class="address-content-row delete-address-row" @click="deleteAddress" v-if="id !==''&& addressList.length >1 && !isDefault">
                <span class="title">删除地址</span>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue, Watch} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import NavBar from "@/components/aui/NavBar.vue";
    import NumberBox from "@/components/aui/NumberBox.vue";


    import CommonUnit from "@/unit/CommonUnit";

    @Component({
        components: {
            NavBar
        }
    })
    export default class AddressEdit extends Scene {

        private districtJsonList: any[] = [];
        private cascadePicker: any = "";
        private addressData: any = {
            detail: {
                name: "",
                phone: "",
                detail: "",
                province_id: "",
                city_id: "",
                region_id: "",
            },
            region: ["", "", ""]
        };
        private addressList: any[] = [];
        private defaultId: number = -1;
        private isDefault: boolean = false;
        private disabled: boolean = false;

        @State("UserStore")
        public user!: InterfaceUser;

        private get regionText(): string {
            return (this.addressData.region || []).join(" ");
        }

        private get addressSaveUrl(): string {
            if (Number(this.$route.query.id || 0) > 0) {
                return this.api.addressEdit;
            }
            return this.api.addressAdd;
        }


        private get id(): string {
            return String(this.$route.query.id || "");
        }

        private back() {
            this.navigateBack();
        }

        private get saveParameter(): any {
            const parameter: any = {
                name: this.addressData.detail.name,
                phone: this.addressData.detail.phone,
                region: this.addressData.region.join(","),
                detail: this.addressData.detail.detail
            };
            if (Number(this.$route.query.id) > 0) {
                parameter.address_id = this.$route.query.id;
            }
            return parameter;
        }

        private mounted() {
            Http.read(this.api.addressJson).then((res) => {
                this.districtJsonList = res;
                this.cascadePicker = (<any> this).$createCascadePicker({
                    title: "请选择所在地区",
                    data: res,
                    onSelect: this.selectCascadePickerItem
                });
            });

            Http.post(this.api.addressList, {}, {token: this.user.token}).then((res) => {
                if (res.code === 1) {
                    this.addressList.push(...res.data.list);
                    this.defaultId = res.data.default_id || 0;
                    this.$nextTick(() => {
                        if (this.addressList.length === 0 || this.id === String(this.defaultId)) {
                            this.isDefault = true;
                            this.disabled = true;
                        }
                    });
                }
            });
            if (this.id) {
                Http.post(this.api.addressDetail, {address_id: this.id}, {token: this.user.token}).then((res) => {
                    if (res.code === 1) {
                        this.addressData = res.data;
                    } else {
                        (<any> this).$createToast({
                            txt: res.msg,
                            mask: true,
                            type: "error",
                            onTimeout: () => {
                                if (!CommonUnit.responseLoginVerification(res)) {
                                    this.navigateLoginPage();
                                }
                            }
                        }).show();
                    }
                });
            }
        }

        private showCascadePicker(): void {
            this.cascadePicker.show();
        }

        private selectCascadePickerItem(selectedVal: any, selectedIndex: any, selectedText: any): void {
            this.$set(this.addressData.region, 0, selectedText[0]);
            this.$set(this.addressData.region, 1, selectedText[1]);
            this.$set(this.addressData.region, 2, selectedText[2]);

            this.addressData = Object.assign(this.addressData, {province_id: selectedVal[0], city_id: selectedVal[1], region_id: selectedVal[2]});
            // this.addressData.province_id = selectedVal[0];
            // this.addressData.city_id = selectedVal[1];
            // this.addressData.region_id = selectedVal[2];
        }

        private save() {
            Http.post(this.addressSaveUrl, {...this.saveParameter}, {token: this.user.token}).then((res) => {
                if (res.code === 1) {
                    if (this.isDefault) {
                        Http.post(this.api.addressSetDefault, {address_id: this.id !== "" ? this.id : res.data.address_id}, {token: this.user.token}).finally(() => {
                        });
                    }
                    (<any> this).$createToast({
                        txt: "收货地址保存成功",
                        mask: true,
                        type: "correct",
                        time: 1500,
                        onTimeout: () => {
                            this.navigateBack();
                        }
                    }).show();


                } else {
                    (<any> this).$createToast({
                        txt: res.msg,
                        mask: true,
                        type: "error",
                        onTimeout: () => {
                            if (!CommonUnit.responseLoginVerification(res)) {
                                this.navigateLoginPage();
                            }
                        }
                    }).show();
                }
            });
        }

        private deleteAddress(): void {
            Http.post(this.api.addressDelete, {address_id: this.id}, {token: this.user.token}).then((res) => {
                if (res.code === 1) {
                    (<any> this).$createToast({
                        txt: "删除地址成功",
                        mask: true,
                        type: "correct",
                        time: 1500,
                        onTimeout: () => {
                            this.navigateBack();
                        }
                    }).show();
                }
            });
        }

    }
</script>

<style scoped lang="stylus">
    .view
        background $theme-page-common-background-color;
        height 100vh;
        width 100vw;

        .save
            color $theme-common-color;
            font-size 13px;

        .address-content
            margin-top 10px;

            .address-content-row
                display flex;
                align-items center;
                position relative;
                overflow hidden;
                padding 0 15px;
                height 55px;
                background #fff;

                &::after
                    content '';
                    position absolute;
                    height 1px;
                    background #ccc;
                    bottom 0;
                    width 100%
                    transform scaleY(.5);

                .title
                    flex-shrink 0;
                    width 75px;
                    font-size 15px;
                    color #333;

                input
                    flex 1;
                    height 55px;

                    &::-webkit-input-placeholder
                        color #aaa

                .div-input
                    flex 1;
                    font-size 15px;
                    color #aaa;

                .iconfont
                    font-size 18px;
                    color $theme-common-color;

            .default-address-row
                margin-top 10px;
                justify-content space-between;

                &::after
                    display none;

                .default-address-switch
                    float right;
                    transform: translateX(8px) scale(.9);

            .delete-address-row
                margin-top 40px;
                height 45px;
                justify-content center;
                align-items center;

                span.title
                    color $theme-warm-color;

</style>